package com.sanpu.kxe.business.main.presenter;

import com.sanpu.kxe.business.main.bean.ReferrerOutput;
import com.sanpu.kxe.business.main.contract.MyReferrerContract;
import com.sanpu.kxe.business.main.model.MainModel;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：我的推荐人
 * Created by 薛勇军 on 2018/7/12.
 */

public class MyReferrerPresenter implements MyReferrerContract.Presenter{

    private MyReferrerContract.View mView;

    private CompositeSubscription mSubscription;

    public MyReferrerPresenter(MyReferrerContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void getReferrerUserInfo() {
        Subscription subscription = MainModel.getInstance().getReferrerUserInfo()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ReferrerOutput>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ReferrerOutput referrerOutput) {
                        if (referrerOutput != null) {
                            ReferrerOutput output = CacheManage.getInstance().getCache(CacheModel.REFERRER_INFO);
                            if (!referrerOutput.equals(output)) {
                                CacheManage.getInstance().saveCache(CacheModel.REFERRER_INFO, referrerOutput);
                                mView.showView();
                            }
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onDestroyPresenter() {
        if (mView != null) {
            mView = null;
        }
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
    }
}
